from datetime import datetime
from enum import Enum
from typing import Dict
import pymysql
from db_decorator_apply import public_con_my_sql
from config import config_instance


public_document_conn = pymysql.connect(**config_instance.public_document_conn_config)


class PublicDocumentStatus(Enum):
    WAITING_FOR_SIGNATURE = '待签收'
    VIEWED = '已查看'
    SIGNED = '已签收'
    SIGN_FAILED = '签收失败'

def get_all_documents():
    """
    获取所有公文记录。

    :return: 如果找到记录，返回记录列表；如果未找到或出现异常，返回空列表
    """
    result = public_con_my_sql(("SELECT * FROM public_documents"), (), public_document_conn)

    if isinstance(result, tuple) and issubclass(result[0], Exception):
        print(f"Error finding all documents: {result[1]}")
        return []
    else:
        documents = result.fetchall()
        if documents:
            return documents
        else:
            print("No documents found.")
            return []


def get_public_document_list(receiving_unit):
    """
    根据接受单位字段寻找签收失败和待签收状态的公共公文记录。

    :param receiving_unit: 接受单位名称
    :return: 如果找到符合条件记录，返回记录列表；如果未找到或出现异常，返回空列表
    """
    query = "SELECT * FROM public_documents WHERE receiving_unit = %s"
    params = (receiving_unit,)
    try:
        documents = public_con_my_sql(query, params, public_document_conn)
        if documents:
            return documents
        else:
            # print("No matching documents found.")
            return []
    except Exception as e:
        print("公共公文数据库类错误：",str(e))
        return []


def insert_public_document(document: Dict):
    """
    将传入的公文字典对应的公文信息插入到public_documents表中。

    :param document: 包含公文各项信息的字典
    :return: 如果插入成功返回True，出现异常返回False
    """
    try:
        query = "INSERT INTO public_documents (title, drafting_unit, receiving_unit, encrypted_sm4_key, sm4_iv,encrypted_data, sm3_signature, status) VALUES (%(title)s, %(drafting_unit)s, %(receiving_unit)s, %(encrypted_sm4_key)s, %(sm4_iv)s,%(encrypted_data)s, %(sm3_signature)s, %(status)s)"
        document['status'] = PublicDocumentStatus.WAITING_FOR_SIGNATURE.value
        params = {
            "title": document['title'],
            "drafting_unit": document['drafting_unit'],
            "receiving_unit": document['receiving_unit'],
            "encrypted_sm4_key": "encrypted_sm4_key",
            "sm4_iv": "sm4_iv",
            "encrypted_data": document,
            "sm3_signature": "sm3_signature",
            "status": PublicDocumentStatus.WAITING_FOR_SIGNATURE.value
        }
        # print("params:",params )
        public_con_my_sql(query, params, public_document_conn)
        return True
    except Exception as e:
        print("插入公文数据库类错误：", str(e))
        return False


def get_public_document_by_id(document_id):
    """
    根据公文ID获取对应的公共公文记录。

    :param document_id: 公文的唯一标识符（ID）
    :return: 如果找到符合条件记录，返回记录列表（通常一条记录，取决于数据库设计情况）；如果未找到或出现异常，返回空列表
    """
    query = "SELECT * FROM public_documents WHERE id = %s"
    params = (document_id,)
    try:
        document = public_con_my_sql(query, params, public_document_conn)
        if document:
            return document[0]
        else:
            print("No matching document found with the given ID.")
            return []
    except Exception as e:
        print("公共公文数据库类错误：", str(e))
        return []


def update_public_document_view_status(document_id):
    new_status = PublicDocumentStatus.VIEWED
    update_public_document_status(document_id, new_status)

def update_public_document_sign_status(document_id,is_success):
    if is_success:
        new_status = PublicDocumentStatus.SIGNED
    else:
        new_status = PublicDocumentStatus.SIGN_FAILED
    update_public_document_status(document_id, new_status)


def update_public_document_status(document_id, new_status):
    """
    根据公文ID更新公共公文的状态以及接受时间。

    :param document_id: 公文的唯一标识符（ID）
    :param new_status: 要更新成的新状态，类型为PublicDocumentStatus枚举中的值
    :return: 如果更新成功返回True，出现异常返回False
    """
    try:
        # 获取当前时间，格式化为数据库合适的时间格式（例如MySQL的DATETIME格式为'%Y-%m-%d %H:%M:%S'）
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        query = "UPDATE public_documents SET status = %s, receive_time = %s WHERE id = %s"
        params = (new_status.value, current_time, document_id)
        public_con_my_sql(query, params, public_document_conn)
        return True
    except Exception as e:
        print("更新公文状态数据库类错误：", str(e))
        return False

